#include "contents.hpp"
#include "fs.hpp"
#include "ui_contents.h"
#include "common.hpp"

static char *codecs[] = {"UTF-8", "UTF-16", "KOI8-R", "CP1251", "CP866", "ISO-8859-5", NULL};

Contents::Contents(QWidget *parent):QWidget(parent)
{
	fs = 0;
	ui = new Ui_Contents;
	ui->setupUi(this);
	ui->text->setDocument(&td);
	codeset = "";
}

void Contents::contextMenuEvent ( QContextMenuEvent * event )
{
	log("Contents: context menu requested \n");
	QMenu menu;
	for(char **it = codecs; *it; it++){
		menu.addAction(*it);
	}
	
	QAction *action = menu.exec(mapToGlobal(event->pos()));
	if(action){
		this->codeset = action->text().toAscii();
		reloadText();
	}
}

#define MAXSIZE (1024*1024*1)
void Contents::reloadText()
{
	//log
	log("Contents: setFile %s \n", curFile.toAscii().data());

	//stat
	FileInfo fi;
	fs->stat(curFile, &fi);
	size_t size = (fi.size > MAXSIZE) ? MAXSIZE : fi.size;
	
	//read file from fs
	QByteArray array(size, 0);
	int bytes_read = fs->read(curFile, array.data(), size);
	if( bytes_read < 0 ){
		perror("Contents: read failed");
		return;
	}

	//convert from current codeset
	QTextCodec *tc = !this->codeset.isEmpty() ? QTextCodec::codecForName(this->codeset.toAscii()) : QTextCodec::codecForLocale();
	QString text = tc->toUnicode(array.data(), bytes_read);
	
	td.setPlainText(text);
}

void Contents::setFile(const QModelIndex& index)
{
	if(!fs)
		return;
	
	QString newFile = index.model()->data(index, Qt::ToolTipRole).toString();
	if( curFile == newFile )
		return;
	else
		curFile = newFile;

	reloadText();
}
